package com.example.demo_pc.util;

/**
 * @Description :
 * @Author : wanghao
 * @Date: 2020-11-23 14:18
 */
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.util.List;

public class DownloadImage {
    private static final Logger logger = LoggerFactory.getLogger(DownloadImage.class);

    public static int downLoadFromUrl(String urlStr, String fileName, String savePath,int num) throws Exception{
        InputStream inputStream=null;
        FileOutputStream fos=null;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置超时间为3秒
            conn.setConnectTimeout(8 * 1000);

            // 防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            // 得到输入流
            inputStream = conn.getInputStream();
            // 获取自己数组
            byte[] getData = readInputStream(inputStream);
            // 文件保存位置
            File saveDir = new File(savePath);
            if (!saveDir.exists()) {
                saveDir.mkdir();
            }
            File file = new File(saveDir + File.separator + fileName);
            fos = new FileOutputStream(file);
            fos.write(getData);

            System.out.println("info:" + urlStr + " download success");
            return 1;
        }catch (FileNotFoundException e){
            if (num==10){
                e.printStackTrace();
            }
            return 0;
        } catch (Exception e){
            if (num==10){
                e.printStackTrace();
            }
           return 2;
        }finally {
            if (fos != null) {
                fos.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }

    }

    private static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }


    public static void download(String urlStr,String filename,String savePath) throws IOException {

        URL url = new URL(urlStr);
        //打开url连接
        InputStream in = url.openStream();
        //请求超时时间
        //输入流
        //缓冲数据
        byte [] bytes = new byte[2048];
        //数据长度
        int len;
        //文件
        File file = new File(savePath);
        if(!file.exists())
            file.mkdirs();

        OutputStream out  = new FileOutputStream(file.getPath()+"\\"+filename);
        //先读到bytes中
        while ((len=in.read(bytes))!=-1){
            //再从bytes中写入文件
            out.write(bytes,0,len);
        }
        //关闭IO
        out.close();
        in.close();

    }

    /***
     * 下载图片
     *
     * @param listImgSrc
     */
    private void Download(List<String> listImgSrc) {
        try {
            for (String url : listImgSrc) {
                String imageName = url.substring(url.lastIndexOf("/") + 1, url.length());
                URL uri = new URL(url);
                InputStream in = uri.openStream();
                FileOutputStream fo = new FileOutputStream(new File(imageName));
                byte[] buf = new byte[1024];
                int length = 0;
                System.out.println("开始下载:" + url);
                while ((length = in.read(buf, 0, buf.length)) != -1) {
                    fo.write(buf, 0, length);
                }
                in.close();
                fo.close();
                System.out.println(imageName + "下载完成");
            }
        } catch (Exception e) {
            System.out.println("下载失败");
        }
    }
    public static boolean downloadImage(String urlStr,String filename,String savePath,int num) {
        boolean isSuccess = false;
        URL url = null;
        try {
            url = new URL(urlStr);
            File file = new File(savePath);
            if(!file.exists())
                file.mkdirs();
            String s = file.getPath() + "/" + filename;
            isSuccess = ImageIO.write(ImageIO.read(url.openStream()),"jpg", new File(s));
            return isSuccess;
        }  catch (Exception e) {
            if (num==15){
                e.printStackTrace();
                System.out.println("下载异常: "+urlStr);
                e.printStackTrace();
            }
            return isSuccess;
        }
    }

    public static boolean imgDownLoad(String urlStr,String filename,String savePath,int num){
        try {
            URL url =new URL(urlStr);
            ReadableByteChannel readableByteChannel = Channels.newChannel(url.openStream());
            File file = new File(savePath);
            if(!file.exists()) {
                file.mkdirs();
            }
            String s = file.getPath() + "/" + filename;
            FileOutputStream fileOutputStream = new FileOutputStream(s);
            FileChannel fileChannel = fileOutputStream.getChannel();
            fileChannel.transferFrom(readableByteChannel, 0, Long.MAX_VALUE);
            return true;
        }catch (Exception e){
            if (num==15){
                e.printStackTrace();
                System.out.println("下载异常: "+urlStr);
                e.printStackTrace();
            }
            return false;
        }

    }
}